Sign Object
Sign வகுப்பு Node.js இன் crypto தொகுதியின் ஒரு பகுதியாகும். இது கிரிப்டோகிராஃபிக் டிஜிட்டல் கையொப்பங்களை உருவாக்க ஒரு வழியை வழங்குகிறது. Sign நிகழ்வுகள் crypto.createSign() முறையைப் பயன்படுத்தி உருவாக்கப்படுகின்றன.
டிஜிட்டல் கையொப்பங்கள் ஒரு செய்தியின் உண்மையான தன்மை மற்றும் ஒருமைப்பாட்டைச் சரிபார்க்க உங்களை அனுமதிக்கின்றன, அது அறியப்பட்ட அனுப்புநரால் உருவாக்கப்பட்டது மற்றும் பரிமாற்றத்தில் மாற்றப்படவில்லை என்பதை உறுதிப்படுத்துகின்றன.
Import Crypto Module
// Import the crypto module
const crypto = require('crypto');
// Create a Sign object
const sign = crypto.createSign('RSA-SHA256');
Sign Methods
| முறை | விளக்கம் |
|---|---|
| sign.update(data[, inputEncoding]) | கொடுக்கப்பட்ட தரவுடன் Sign உள்ளடக்கத்தைப் புதுப்பிக்கிறது. inputEncoding வழங்கப்பட்டால், தரவு குறிப்பிட்ட குறியீட்டைப் பயன்படுத்தி ஒரு சரமாகும்; இல்லையெனில், தரவு ஒரு Buffer, TypedArray, அல்லது DataView ஆகும். இந்த முறை புதிய தரவுடன் பல முறை அழைக்கப்படலாம். |
| sign.sign(privateKey[, outputEncoding]) | sign.update() ஐப் பயன்படுத்தி அனுப்பப்பட்ட அனைத்து தரவின் கையொப்பத்தைக் கணக்கிடுகிறது. privateKey என்பது PEM-குறியிடப்பட்ட தனிப்பட்ட விசையைக் கொண்ட ஒரு சரம் அல்லது buffer, அல்லது 'private' வகையின் KeyObject ஆகும். outputEncoding வழங்கப்பட்டால், ஒரு சரம் திரும்பும்; இல்லையெனில், ஒரு Buffer திரும்பும். |
Basic Sign Example
பின்வரும் எடுத்துக்காட்டு ஒரு செய்தியின் டிஜிட்டல் கையொப்பத்தை எவ்வாறு உருவாக்குவது என்பதை விளக்குகிறது:
const crypto = require('crypto');
const fs = require('fs');
// Generate a keypair for this example
function generateKeyPair() {
return crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
}
// For this example, generate keys in memory
// In a real application, you would load existing keys from storage
const { privateKey, publicKey } = generateKeyPair();
// Message to sign
const message = 'This is a message to be signed';
// Create a Sign object
const sign = crypto.createSign('SHA256');
// Update with the message
sign.update(message);
// Sign the message with the private key
const signature = sign.sign(privateKey, 'hex');
console.log('Message:', message);
console.log('Signature:', signature);
// We'll save these for the verification example
fs.writeFileSync('message.txt', message);
fs.writeFileSync('signature.hex', signature);
fs.writeFileSync('public_key.pem', publicKey);
Signing with Different Algorithms
Sign வகுப்பு கிரிப்டோ வழங்கியைப் பொறுத்து பல்வேறு கையொப்ப அல்காரிதம்களை ஆதரிக்கிறது:
const crypto = require('crypto');
// Generate key pairs for different algorithms
function generateRSAKeyPair() {
return crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
}
function generateECKeyPair() {
return crypto.generateKeyPairSync('ec', {
namedCurve: 'prime256v1',
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'sec1',
format: 'pem'
}
});
}
// Generate different key pairs
const rsaKeys = generateRSAKeyPair();
const ecKeys = generateECKeyPair();
// Message to sign
const message = 'Message to sign with different algorithms';
// Function to sign with a specific algorithm
function signWithAlgorithm(algorithm, privateKey, message) {
try {
const sign = crypto.createSign(algorithm);
sign.update(message);
return sign.sign(privateKey, 'hex');
} catch (error) {
return `Error: ${error.message}`;
}
}
// Test various signature algorithms
console.log(`Message: "${message}"`);
console.log('-----------------------------------------------');
// RSA signatures with different hash algorithms
console.log('RSA-SHA256:', signWithAlgorithm('SHA256', rsaKeys.privateKey, message));
console.log('RSA-SHA384:', signWithAlgorithm('SHA384', rsaKeys.privateKey, message));
console.log('RSA-SHA512:', signWithAlgorithm('SHA512', rsaKeys.privateKey, message));
console.log('-----------------------------------------------');
// ECDSA signatures
console.log('ECDSA-SHA256:', signWithAlgorithm('SHA256', ecKeys.privateKey, message));
console.log('ECDSA-SHA384:', signWithAlgorithm('SHA384', ecKeys.privateKey, message));
கையொப்ப அல்காரிதம்கள் உங்கள் Node.js பதிப்பு மற்றும் நிறுவப்பட்ட OpenSSL பதிப்பைப் பொறுத்தது. பொதுவான கையொப்ப அல்காரிதம்கள் அடங்கும்:
| அல்காரிதம் | விளக்கம் | விசை வகைகள் |
|---|---|---|
| RSA-SHA256 | SHA-256 ஹாஷ் உடன் RSA கையொப்பம் | RSA |
| RSA-SHA384 | SHA-384 ஹாஷ் உடன் RSA கையொப்பம் | RSA |
| RSA-SHA512 | SHA-512 ஹாஷ் உடன் RSA கையொப்பம் | RSA |
| RSA-PSS-SHA256 | SHA-256 ஹாஷ் உடன் RSA-PSS கையொப்பம் | RSA |
| ECDSA-SHA256 | SHA-256 ஹாஷ் உடன் ECDSA கையொப்பம் | EC |
| ECDSA-SHA384 | SHA-384 ஹாஷ் உடன் ECDSA கையொப்பம் | EC |
| Ed25519 | Curve25519 ஐப் பயன்படுத்தும் EdDSA கையொப்பம் | Ed25519 |
| Ed448 | Curve448 ஐப் பயன்படுத்தும் EdDSA கையொப்பம் | Ed448 |
Signing with Multiple Updates
கையொப்பத்தைக் கணக்கிடுவதற்கு முன் பல தரவுத் துண்டுகளுடன் ஒரு Sign பொருளைப் புதுப்பிக்கலாம்:
const crypto = require('crypto');
// Generate a keypair for this example
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
// Create a Sign object
const sign = crypto.createSign('SHA256');
// Update with multiple pieces of data
sign.update('First part of the message. ');
sign.update('Second part of the message. ');
sign.update('Third part of the message.');
// Create the signature
const signature = sign.sign(privateKey, 'hex');
console.log('Combined message: First part of the message. Second part of the message. Third part of the message.');
console.log('Signature:', signature);
// You can achieve the same result with a single update
const singleSign = crypto.createSign('SHA256');
singleSign.update('First part of the message. Second part of the message. Third part of the message.');
const singleSignature = singleSign.sign(privateKey, 'hex');
console.log('Single update signature matches multiple updates?', singleSignature === signature);
Signing Files
நீங்கள் ஒரு கோப்பின் உள்ளடக்கங்களுக்கான டிஜிட்டல் கையொப்பத்தை உருவாக்கலாம்:
const crypto = require('crypto');
const fs = require('fs');
// Function to sign a file
function signFile(filePath, privateKey, algorithm = 'SHA256') {
return new Promise((resolve, reject) => {
// Create Sign object
const sign = crypto.createSign(algorithm);
// Create read stream
const readStream = fs.createReadStream(filePath);
// Handle stream events
readStream.on('data', (data) => {
sign.update(data);
});
readStream.on('end', () => {
// Create signature
const signature = sign.sign(privateKey, 'hex');
resolve(signature);
});
readStream.on('error', (error) => {
reject(error);
});
});
}
// Generate a keypair for this example
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
// Save the public key for verification
fs.writeFileSync('public_key_file.pem', publicKey);
// Example usage (adjust file path as needed)
const filePath = 'example_to_sign.txt';
// Create a test file if it doesn't exist
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, 'This is a test file for digital signature.\n'.repeat(100));
console.log(`Created test file: ${filePath}`);
}
// Sign the file
signFile(filePath, privateKey)
.then(signature => {
console.log(`File: ${filePath}`);
console.log(`Signature: ${signature}`);
// Save the signature for later verification
fs.writeFileSync(`${filePath}.sig`, signature);
console.log(`Signature saved to: ${filePath}.sig`);
})
.catch(error => {
console.error('Error signing file:', error.message);
});
Using Different Types of Keys
Sign வகுப்பு தனிப்பட்ட விசைகளின் வெவ்வேறு வடிவங்களுடன் வேலை செய்யலாம்:
const crypto = require('crypto');
// Message to sign
const message = 'Message to sign with different key formats';
// Function to sign with different key formats
function signWithKey(privateKey, keyFormat) {
try {
const sign = crypto.createSign('SHA256');
sign.update(message);
return {
format: keyFormat,
signature: sign.sign(privateKey, 'hex')
};
} catch (error) {
return {
format: keyFormat,
error: error.message
};
}
}
// Generate a new RSA key pair
const { privateKey: pemPrivateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
console.log(`Message: "${message}"`);
// 1. Sign with PEM-encoded private key (string)
console.log('\n1. PEM-encoded private key (string):');
console.log(signWithKey(pemPrivateKey, 'PEM string'));
// 2. Sign with PEM-encoded private key (buffer)
console.log('\n2. PEM-encoded private key (buffer):');
console.log(signWithKey(Buffer.from(pemPrivateKey), 'PEM buffer'));
// 3. Sign with KeyObject
console.log('\n3. KeyObject:');
const keyObject = crypto.createPrivateKey(pemPrivateKey);
console.log(signWithKey(keyObject, 'KeyObject'));
// 4. Sign with PassThrough crypto engine (if available)
try {
// Note: This might not be available in all Node.js versions/configurations
console.log('\n4. Private key with engine:');
const engineKey = {
key: pemPrivateKey,
padding: crypto.constants.RSA_PKCS1_PADDING
};
console.log(signWithKey(engineKey, 'Key with options'));
} catch (error) {
console.log('\n4. Private key with engine:');
console.log({ format: 'Key with options', error: error.message });
}
// 5. Sign with JSON Web Key (JWK)
// Note: This requires conversion, as Node.js doesn't directly support JWK for sign
console.log('\n5. JWK (requires conversion):');
try {
// This is a simplified example - actual JWK handling would be more complex
const pemToJwk = require('pem-jwk').pem2jwk; // You would need to install this package
const jwk = pemToJwk(pemPrivateKey);
console.log({ format: 'JWK', note: 'JWK needs to be converted to PEM or KeyObject first' });
} catch (error) {
console.log({ format: 'JWK', note: 'Example requires pem-jwk package' });
}
Complete Sign and Verify Example
இந்த எடுத்துக்காட்டு டிஜிட்டல் கையொப்பத்தை உருவாக்குவதற்கும் சரிபார்க்கவும் முழுமையான செயல்முறையை விளக்குகிறது:
const crypto = require('crypto');
// Generate a keypair
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
// Original message
const message = 'This is the original message to sign and verify';
console.log(`Original message: "${message}"`);
// Sign the message
function signMessage(message, privateKey) {
const sign = crypto.createSign('SHA256');
sign.update(message);
return sign.sign(privateKey, 'hex');
}
const signature = signMessage(message, privateKey);
console.log(`Signature: ${signature}`);
// Verify the message (using the Verify class)
function verifySignature(message, signature, publicKey) {
const verify = crypto.createVerify('SHA256');
verify.update(message);
return verify.verify(publicKey, signature, 'hex');
}
// Verify the original message
const isValidOriginal = verifySignature(message, signature, publicKey);
console.log(`Original message verification: ${isValidOriginal}`);
// Try to verify a tampered message
const tamperedMessage = message + ' with some tampering';
const isValidTampered = verifySignature(tamperedMessage, signature, publicKey);
console.log(`Tampered message verification: ${isValidTampered}`);
// Try to use a different public key
const { publicKey: differentPublicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
const isValidDifferentKey = verifySignature(message, signature, differentPublicKey);
console.log(`Verification with different public key: ${isValidDifferentKey}`);
DSA and ECDSA Signatures
இந்த எடுத்துக்காட்டு டிஜிட்டல் கையொப்பங்களுக்கு DSA மற்றும் ECDSA ஐப் பயன்படுத்துவதை விளக்குகிறது:
const crypto = require('crypto');
// Message to sign
const message = 'Message for DSA and ECDSA signatures';
// Generate ECDSA key pair
function generateECKeyPair(curveName = 'prime256v1') {
return crypto.generateKeyPairSync('ec', {
namedCurve: curveName,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'sec1', // or 'pkcs8'
format: 'pem'
}
});
}
// Function to sign and verify with a specific algorithm and key pair
function testSignatureAlgorithm(algorithm, keyType, keyPair, message) {
try {
// Sign the message
const sign = crypto.createSign(algorithm);
sign.update(message);
const signature = sign.sign(keyPair.privateKey, 'hex');
// Verify the signature
const verify = crypto.createVerify(algorithm);
verify.update(message);
const isValid = verify.verify(keyPair.publicKey, signature, 'hex');
return {
algorithm: `${keyType}-${algorithm}`,
signatureLength: signature.length / 2, // Convert hex to bytes
isValid
};
} catch (error) {
return {
algorithm: `${keyType}-${algorithm}`,
error: error.message
};
}
}
// Test ECDSA with different curves
const curves = ['prime256v1', 'secp384r1', 'secp521r1'];
console.log(`Message: "${message}"`);
console.log('\nECDSA Signatures:');
curves.forEach(curve => {
const ecKeyPair = generateECKeyPair(curve);
// Test with different hash algorithms
const hashAlgos = ['SHA256', 'SHA384', 'SHA512'];
hashAlgos.forEach(hashAlgo => {
const result = testSignatureAlgorithm(hashAlgo, `ECDSA-${curve}`, ecKeyPair, message);
console.log(result);
});
});
// Test EdDSA if available
try {
console.log('\nEdDSA Signatures:');
// Ed25519
const ed25519KeyPair = crypto.generateKeyPairSync('ed25519', {
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
// Sign with Ed25519
const sign = crypto.createSign('SHA512'); // Hash algorithm is ignored for Ed25519
sign.update(message);
const signature = sign.sign(ed25519KeyPair.privateKey, 'hex');
// Verify with Ed25519
const verify = crypto.createVerify('SHA512');
verify.update(message);
const isValid = verify.verify(ed25519KeyPair.publicKey, signature, 'hex');
console.log({
algorithm: 'Ed25519',
signatureLength: signature.length / 2,
isValid
});
} catch (error) {
console.log({
algorithm: 'Ed25519',
error: error.message
});
}
Signing with OpenSSL Options
குறிப்பிட்ட OpenSSL விருப்பங்களுடன் மேம்பட்ட கையொப்பமிடுதல்:
const crypto = require('crypto');
// Generate RSA key pair
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
// Message to sign
const message = 'Message to sign with different options';
// Function to sign with specific options
function signWithOptions(algorithm, message, privateKey, options = {}) {
try {
// Create private key with options
const keyWithOptions = {
key: privateKey,
...options
};
// Sign the message
const sign = crypto.createSign(algorithm);
sign.update(message);
return sign.sign(keyWithOptions, 'hex');
} catch (error) {
return `Error: ${error.message}`;
}
}
console.log(`Message: "${message}"`);
console.log('\nRSA Signatures with Different Options:');
// 1. Standard PKCS#1 v1.5 padding (default)
console.log('\n1. Standard PKCS#1 v1.5 padding:');
const sig1 = signWithOptions('SHA256', message, privateKey);
console.log(sig1);
// 2. PSS padding
console.log('\n2. PSS padding:');
const sig2 = signWithOptions('SHA256', message, privateKey, {
padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
saltLength: 32
});
console.log(sig2);
// 3. Different salt lengths with PSS padding
console.log('\n3. PSS padding with different salt lengths:');
[20, 32, 48].forEach(saltLength => {
try {
const sigSalt = signWithOptions('SHA256', message, privateKey, {
padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
saltLength
});
console.log(`Salt length ${saltLength}: ${sigSalt.substring(0, 64)}...`);
} catch (error) {
console.log(`Salt length ${saltLength}: Error - ${error.message}`);
}
});
// 4. Try to use no padding (will likely fail for signatures)
console.log('\n4. No padding (expect error):');
const sig4 = signWithOptions('SHA256', message, privateKey, {
padding: crypto.constants.RSA_NO_PADDING
});
console.log(sig4);
Security Best Practices
டிஜிட்டல் கையொப்பங்களைப் பயன்படுத்தும் போது, இந்த பாதுகாப்பு சிறந்த நடைமுறைகளைக் கவனியுங்கள்:
Common Use Cases for Digital Signatures
Code Signing
மென்பொருள் தொகுப்புகள், இயக்கக்கூடிய கோப்புகள் அல்லது ஸ்கிரிப்ட்களை அவற்றின் உண்மையான தன்மை மற்றும் ஒருமைப்பாட்டைச் சரிபார்க்க கையொப்பமிடுதல்
Document Signing
PDFகள் மற்றும் பிற ஆவணங்களுக்கு சட்டபூர்வமாக கட்டுப்படும் மின்னணு கையொப்பங்களை உருவாக்குதல்
JWT Signing
பாதுகாப்பான அங்கீகாரம் மற்றும் அங்கீகாரத்திற்கான JSON Web Tokens (JWTs) கையொப்பமிடுதல்
API Authentication
API கிளையன்ட்களின் அடையாளத்தைச் சரிபார்த்தல் மற்றும் கோரிக்கை ஒருமைப்பாட்டை உறுதிப்படுத்துதல்
Certificate Signing
PKI அமைப்பில் சான்றிதழ் சங்கிலிகளை உருவாக்குதல் மற்றும் சரிபார்த்தல்
Secure Communication
பாதுகாப்பான தகவல் தொடர்பு நெறிமுறைகளில் செய்திகளை அங்கீகரித்தல்